package com.draven.system.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.draven.common.entity.NoteTag;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 笔记标签Mapper接口
 * 
 * @author draven
 */
@Mapper
public interface NoteTagMapper extends BaseMapper<NoteTag> {

    /**
     * 查询标签列表（包含使用次数）
     * 
     * @return 标签列表
     */
    @Select("SELECT t.*, COUNT(r.note_id) as usage_count " +
            "FROM note_tag t " +
            "LEFT JOIN note_tag_relation r ON t.id = r.tag_id AND r.del_flag = 0 " +
            "WHERE t.del_flag = 0 " +
            "GROUP BY t.id " +
            "ORDER BY t.use_count DESC, t.create_time DESC")
    List<NoteTag> selectTagListWithCount();

    /**
     * 根据笔记ID查询标签列表
     * 
     * @param noteId 笔记ID
     * @return 标签列表
     */
    @Select("SELECT t.* FROM note_tag t " +
            "INNER JOIN note_tag_relation r ON t.id = r.tag_id " +
            "WHERE r.note_id = #{noteId} AND t.del_flag = 0 AND r.del_flag = 0 " +
            "ORDER BY r.create_time ASC")
    List<NoteTag> selectTagsByNoteId(@Param("noteId") Long noteId);

    /**
     * 根据标签名称查询标签
     * 
     * @param tagName 标签名称
     * @return 标签信息
     */
    @Select("SELECT * FROM note_tag WHERE tag_name = #{tagName} AND del_flag = 0")
    NoteTag selectByTagName(String tagName);

    /**
     * 获取热门标签（使用次数最多的前N个）
     * 
     * @param limit 限制数量
     * @return 标签列表
     */
    @Select("SELECT * FROM note_tag WHERE del_flag = 0 AND status = 0 " +
            "ORDER BY use_count DESC, create_time DESC LIMIT #{limit}")
    List<NoteTag> selectHotTags(@Param("limit") Integer limit);
}